<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useForm, useFormRules } from "@/hooks/common/form";
import { $t } from "@/locales";
// import { useBoolean } from '@sa/hooks';
// import { enableStatusOptions } from '@/constants/business';
import { ApiRoleOut } from "@/api-services";
import { ApiroleserviceApi } from "@/api-services/apis/apiroleservice-api";
import { feature, getAPI } from "@/axios-utils";
import { queryDone } from "@/utils/api";
import { useBoolean } from "~/packages/hooks/src";
import RoleMenuTree from "./role-menu-tree.vue";

defineOptions({
  name: "RoleOperateModal",
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  rowData?: ApiRoleOut | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: "submitted"): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>("visible", {
  default: false,
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: $t("page.manage.role.addRole"),
    edit: $t("page.manage.role.editRole"),
  };
  return titles[props.operateType];
});

type Model = Pick<
  ApiRoleOut,
  "name" | "code" | "sort" | "isEnable" | "remark"
> & { actionIds: number[] };

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    name: "",
    code: "",
    sort: 0,
    isEnable: true,
    remark: "",
    actionIds: [],
  };
}

type RuleKey = Exclude<
  keyof Model,
  "sort" | "isEnable" | "remark" | "actionIds"
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  code: defaultRequiredRule,
};

const roleId = computed(() => Number(props.rowData?.id || -1));

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === "edit" && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeModal() {
  visible.value = false;
}
const actionIds = ref<number[]>([]);
function updateCheck(checkedIds: number[]) {
  actionIds.value = checkedIds;
}
async function handleSubmit() {
  await validate();
  model.value.actionIds = actionIds.value;
  //提交请求
  const [err, res] = await feature(
    getAPI(ApiroleserviceApi).insertOrUpdate(model.value),
  );

  queryDone(err, async () => {
    if (res?.data.data) {
      window.$message?.success($t("common.updateSuccess"));
      closeModal();
      emit("submitted");
    }
  });
  // request
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

const fullScreen = ref(false);
</script>

<template>
  <NModal v-model:open="visible" :title="title" width="1000px" modal-height="" :show-full-screen="true"
    @handleFullScreenChange="(val) => (fullScreen = val)">
    <ElRow :gutter="16" class="h-full">
      <ElCol :span="12">
        <ElForm ref="formRef" :model="model" :rules="rules" label-width="auto">
          <ElFormItem :label="$t('page.manage.role.roleName')" name="roleName">
            <ElInput v-model="model.name!" :placeholder="$t('page.manage.role.form.roleName')" />
          </ElFormItem>

          <ElFormItem :label="$t('page.manage.role.roleCode')" name="roleCode">
            <ElInput v-model="model.code!" :placeholder="$t('page.manage.role.form.roleCode')" />
          </ElFormItem>

          <ElFormItem :label="$t('page.manage.role.roleStatus')" name="isEnable">
            <ElSwitch v-model:model-value="model.isEnable" />
          </ElFormItem>

          <ElFormItem :label="$t('page.manage.role.sort')" name="sort">
            <ElInput v-model="model.sort" type="number" />
          </ElFormItem>

          <ElFormItem :label="$t('page.manage.role.roleDesc')" name="remark">
            <ElInput type="textarea" v-model="model.remark!" :auto-size="{ minRows: 5, maxRows: 10 }" />
          </ElFormItem>
        </ElForm>
      </ElCol>
      <ElCol :span="12" class="h-full">
        <div :class="fullScreen ? 'h-full  overflow-auto' : 'h-500px overflow-auto'">
          <RoleMenuTree ref="roleMenuTreeRef" v-model:role-id="roleId" @updateCheck="updateCheck"></RoleMenuTree>
        </div>
        <!-- <ButtonAuthModal :visible="visible" :role-id="roleId"></ButtonAuthModal> -->
      </ElCol>
    </ElRow>

    <!-- <ElSpace v-if="isEdit">
      <ElButton @click="openMenuAuthModal">{{ $t('page.manage.role.menuAuth') }}</ElButton>
      <MenuAuthModal v-model:visible="menuAuthVisible" :role-id="roleId" />
      <ElButton @click="openButtonAuthModal">{{ $t('page.manage.role.buttonAuth') }}</ElButton>
      <ButtonAuthModal v-model:visible="buttonAuthVisible" :role-id="roleId" />
    </ElSpace> -->
    <template #footer>
      <div class="flex-y-center justify-end gap-12px">
        <ElButton @click="closeModal">{{ $t("common.cancel") }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{
          $t("common.confirm")
          }}</ElButton>
      </div>
    </template>
  </NModal>
</template>

<style scoped></style>
